package com.example.springboot.controller;

import com.example.springboot.common.Result;
import com.example.springboot.dao.CartDao;
import com.example.springboot.dao.GoodsDao;
import com.example.springboot.dao.OrderDao;
import com.example.springboot.entity.Cart;
import com.example.springboot.entity.Goods;
import com.example.springboot.entity.Order;
import com.example.springboot.entity.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private GoodsDao goodsDao;
    private OrderDao orderDao;
    private CartDao cartDao;

    @Resource
    private RedisTemplate redisTemplate;

    public OrderController(OrderDao orderDao, CartDao cartDao) {
        this.orderDao = orderDao;
        this.cartDao = cartDao;
    }

    @GetMapping
    public Result findByUserid(@RequestParam("userid") String userid){
        return Result.success(orderDao.findByUserid(userid));
    }

    @GetMapping("/findAll")
    public Result findAll(){
        return Result.success(orderDao.findAll());
    }

    @PostMapping("/addOrder")
    public synchronized Result AddOrder(@RequestBody List<Cart> carts){
        BigDecimal total = new BigDecimal(0);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        Order order = new Order();
       for(Cart cart:carts){
           OrderItem orderItem = new OrderItem();
           Goods goods = goodsDao.getById(cart.getGoods_id());
           if(redisTemplate.hasKey("goods:"+goods.getId())){
               int num = (int)redisTemplate.opsForHash().get("goods:"+goods.getId(),"nums");
               num = num - cart.getNum();
               redisTemplate.opsForHash().put("goods:"+goods.getId(),"nums",num);//下单改变商品数量redis
           }
           goodsDao.updataNums(cart.getNum(), goods.getId());//下单改变商品数量mysql
           orderItem.setGoodsId(goods.getId());
           orderItem.setGoodsName(goods.getName());
           orderItem.setImg(goods.getImg());
           orderItem.setNums(cart.getNum());
           orderItem.setPrice(goods.getPrice());
           orderItem.setOrderId(cart.getId());
           orderItem.setOrderON(uuid);
           orderDao.addOrderItem(orderItem);
           total = total.add(goods.getPrice().multiply(BigDecimal.valueOf(cart.getNum())));
           order.setUserid(Integer.valueOf(cart.getUser_id()));
           cartDao.deleteById(cart.getId());
       }
        LocalDateTime dateTime = LocalDateTime.now(); // get the current date and time
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
        order.setOrderOn(uuid);
        order.setCreateTime(dateTime.format(formatter));
        order.setStatus(1);
        order.setTotal(total);
        return Result.success(orderDao.addOrder(order));
    }

    @DeleteMapping("/{id}")
    public Result Delete(@PathVariable Integer id){
        if(id==null||id==0){
            //throw new RuntimeException("参数不可为空");
            Result.error("参数不可为空");
        }
        String orderOn = orderDao.findOrderOn(id);
        orderDao.deleteByOrderOn(orderOn);
        return Result.success(orderDao.deleteById(id)==1);
    }

    @PutMapping
    public Result upData(@RequestBody Order order){
//        System.out.println("222 "+ order.getTotal());
        orderDao.updataSpend(order);
        return Result.success(orderDao.updataStatus(order));
    }

    @PutMapping("/upCancel")
    public Result upCancel(@RequestParam("id") Integer id){
        String orderOn = orderDao.findOrderOn(id);
        List<OrderItem> OrderItems =  orderDao.findOrderItem(orderOn);
        int count = 0;
        for(OrderItem orderItem:OrderItems){
            Integer goodsId = orderItem.getGoodsId();
            Integer nums = orderItem.getNums();
            //System.out.println(goodsId+" "+nums);
            if(redisTemplate.hasKey("goods:"+goodsId)){
                int num = (int)redisTemplate.opsForHash().get("goods:"+goodsId,"nums");
                num = num + nums;
                redisTemplate.opsForHash().put("goods:"+goodsId,"nums",num);//到货前取消订单改变商品数量redis
            }
            int temp =  goodsDao.updataCancleNums(goodsId, nums);//到货前取消订单改变商品数量mysql
            count+=temp;
        }
        orderDao.deleteById(id);
        orderDao.deleteByOrderOn(orderOn);
        if(count>0)return Result.success("取消成功"+count+"个订单已取消");
        return Result.error("取消失败");
    }

}
